package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;

import com.ruoyi.common.entity.Project;
import com.ruoyi.common.entity.ProjectItem;
import com.ruoyi.common.entity.dto.ProjectDetailDTO;
import com.ruoyi.common.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    // 获取所有启用的项目 (示例：分页查询)
    @GetMapping("/items")
    public R<Page<Project>> getProjects(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Project> projectPage = new Page<>(page, size);
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getStatus, 1); // 只查询启用的项目
        projectService.page(projectPage, queryWrapper);
        return R.ok(projectPage);
    }

    // 根据ID获取项目详情
    @GetMapping("/detail/{id}")
    public R<ProjectDetailDTO> getProjectById(@PathVariable Long id) {
        ProjectDetailDTO project = projectService.getProjectDetail(id);
        if (project != null) {
            return R.ok(project);
        } else {
            return R.fail("项目未找到");
        }
    }

    // 创建项目
    @PostMapping
    public R<Project> createProject(@RequestBody Project project) {
        // 这里可以添加创建人等逻辑
        // project.setCreateBy("current_user"); // 示例
        boolean saved = projectService.save(project);
        if (saved) {
            return R.ok(projectService.getById(project.getId())); // 返回完整信息
        } else {
            return R.fail("创建项目失败");
        }
    }

    // 更新项目
    @PutMapping("/{id}")
    public R<String> updateProject(@PathVariable Long id, @RequestBody Project project) {
        project.setId(id); // 确保ID一致
        // 这里可以添加更新人等逻辑
        // project.setUpdateBy("current_user"); // 示例
        boolean updated = projectService.updateById(project);
        if (updated) {
            return R.ok("更新成功");
        } else {
            return R.fail("更新失败");
        }
    }

    // 删除项目 (软删除示例，实际可根据status字段处理)
    @DeleteMapping("/{id}")
    public R<String> deleteProject(@PathVariable Long id) {
        boolean removed = projectService.removeById(id);
        if (removed) {
            return R.ok("删除成功");
        } else {
            return R.fail("删除失败");
        }
    }

    @GetMapping("/Baidu/{id}")
    public R<String> getProjectByIdBaidu(@PathVariable Long id) {
        String project = projectService.getProjectByIdBaidu(id);
        if (project != null) {
            return R.ok(project);
        } else {
            return R.fail("项目未找到");
        }
    }

}